from rest_framework import serializers

from oauth.models import OAuthQQUser
from oauth.utils import check_save_user_token
from users.models import User

"""
QQ登录创建用户序列化器
"""


class QQAuthUserSerializer(serializers.Serializer):
    access_token = serializers.CharField(label='操作凭证')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')

    # 校验
    def validate(self, attrs):
        # 获取参数
        sms_code = attrs.get("sms_code")
        mobile = attrs.get("mobile")
        password = attrs.get("password")
        access_token = attrs.get("access_token")

        # 1 判断短信验证码
        from django_redis import get_redis_connection
        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_%s" % mobile)
        if redis_sms_code is None:
            raise serializers.ValidationError("验证码已过期")
        # redis 中存放的都是二进制数据
        if sms_code != redis_sms_code.decode():
            raise serializers.ValidationError("验证码不正确")

        # 2 判断openid
        openid = check_save_user_token(access_token)
        if not openid:
            raise serializers.ValidationError('无效的access_token')

        # 3 根据手机号判断用户是否注过
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 如果不存在，则创建一个新的用户，并保存
            pass
        else:
            # 如果用户存在，检查用户密码
            if not user.check_password(password):
                raise serializers.ValidationError('密码错误！')

            # attrs = {
            #     "openid": openid,
            #     "user": user
            # }
            attrs["openid"] = openid
            attrs["user"] = user

            return attrs

    def create(self, validated_data):
        user = validated_data.get("user")

        # 如果用户不存在，则新建一个用户
        if not user:
            user = User.objects.create(
                username=validated_data.get("mobile"),
                mobile=validated_data.get("mobile"),
                password=validated_data.get("password")
            )
            # 密码加密
            user.set_password(validated_data.get("password"))
            user.save()

        # 将用户绑定openid
        openid = validated_data.get("openid")
        qquser = OAuthQQUser.objects.create(
            user=user,
            openid=openid["openid"]
        )

        return qquser


